import {onCatchFunc, onCheckDataFunc} from "../expressExt/ExpFunc";
import {Log} from "../expressExt/Log";
import {exp, IFieldRes} from "../expressExt/exp";
import {ExpressExt} from "../expressExt/ExpressExt";
import {ShowAbleErr} from "../expressExt/public/sdf";
import {ViewError} from "../views/ViewError";
import {Request} from "express";
import {Response} from "express";
import {FormParse} from "../expressExt/FormParse";

export class LogicCheck {

    /**
     * 异常处理
     * @param errHtml 是否send html页面
     * @returns {(url:any, modClass:any, req:any, resp:any, err:any)=>undefined}
     */
    static getOncatch(errHtml?: boolean): onCatchFunc {
        return (url, modClass, req, resp, err) => {
            Log.write(url + exp.netErr + " : " + JSON.stringify(req[exp.reqFormDat] || ExpressExt.setReqParas(req)), err);

            if ((err as ShowAbleErr).showMsg)
                resp.status(500).send(errHtml ? ViewError.netError(err.message) : err.message);
            else
                resp.status(500).send(errHtml ? ViewError.netError(exp.netErr) : exp.netErr);
        }
    }

    /**
     * 接口入参验证与登陆验证
     * @param validFunc 登陆验证函数
     * @param errHtml 是否send html页面
     * @returns {(url:any, modClass:any, req:any, resp:any, next:any)=>Promise<undefined>}
     */
    static getOnCheckData(validFunc?: (req: Request, resp: Response, dat: IFieldRes<any>) => Promise<void|boolean>
        , errHtml?: boolean): onCheckDataFunc {
        return async(url, modClass, req, resp, next) => {
            if (!modClass) {
                next({});
                return;
            }
            //入参格式验证
            let check_data = await FormParse.checkReq(modClass, req);
            if (!check_data.ok) {
                Log.write(url + " : " + JSON.stringify(check_data));
                resp.status(500).send(errHtml ? ViewError.netError(check_data.msg) : check_data.msg);
                return;
            }

            let noValid = exp.getNoValid(modClass);
            if (!noValid && validFunc) {
                if ((await validFunc(req, resp, check_data)) === false)
                    return;
            }
            next(check_data.val);

        }
    }
}